/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.pro.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.Collections3;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.pro.entity.ProLog;
import com.thinkgem.jeesite.modules.pro.entity.Project;
import com.thinkgem.jeesite.modules.pro.entity.ProjectTask;
import com.thinkgem.jeesite.modules.pro.entity.ProjectUser;
import com.thinkgem.jeesite.modules.pro.entity.TaskGroup;
import com.thinkgem.jeesite.modules.pro.service.ProLogService;
import com.thinkgem.jeesite.modules.pro.service.ProjectService;
import com.thinkgem.jeesite.modules.pro.service.ProjectTaskService;
import com.thinkgem.jeesite.modules.pro.service.ProjectUserService;
import com.thinkgem.jeesite.modules.pro.service.TaskGroupService;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;

/**
 * 项目管理功能Controller
 * @author fanqinglong
 * @version 2017-04-13
 */
@Controller
@RequestMapping(value = "${adminPath}/pro/project")
public class ProjectController extends BaseController {

	@Autowired
	private ProjectService projectService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private ProLogService proLogService;
	@Autowired
	private ProjectUserService projectUserService;
	@Autowired
	private ProjectTaskService projectTaskService;
	@Autowired
	private TaskGroupService taskGroupService;
	
	@ModelAttribute
	public Project get(@RequestParam(required=false) String id) {
		Project entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = projectService.get(id);
		}
		if (entity == null){
			entity = new Project();
		}
		return entity;
	}
	
	@RequestMapping(value = {"projectTree"})
	public String projectTree(Model model){
		model.addAttribute("tree", projectService.findList(new Project()));
		return "modules/pro/projectTree";
	}
	@RequestMapping(value = {"taskProjectTree"})
	public String taskProjectTree(Model model){
		model.addAttribute("tree", projectService.findList(new Project()));
		return "modules/pro/taskProjectTree";
	}
	
	@RequiresPermissions("pro:project:view")
	@RequestMapping(value = {"list", ""})
	public String list(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Project> page = projectService.findPage(new Page<Project>(request, response), project); 
		model.addAttribute("page", page);
		return "modules/pro/projectList";
	}
	
	@RequiresPermissions("pro:project:edit")
	@RequestMapping(value = "assign")
	public String assign(Project project,Model model){
		List<User> list = systemService.getByProjectId(project.getId());
		project = projectService.get(project.getId());
		model.addAttribute("userList", list);
		model.addAttribute("project", project);
		return "modules/pro/projectAssign";
	}
	
	@RequiresPermissions("pro:project:view")
	@RequestMapping(value = "none")
	public String none() {
		return "modules/pro/groupNone";
	}
	@RequiresPermissions("pro:project:edit")
	@RequestMapping(value = "assignAuth")
	public String assignAuth(String userId,String projectId,Model model) {
		ProjectUser projectUser = new ProjectUser();
		User user = systemService.getUser(userId);
		Project project = projectService.get(projectId);
		projectUser.setUser(user);
		projectUser.setProjectId(projectId);
		ProjectUser result = projectUserService.getByParam(projectUser);
		model.addAttribute("projectUser", result);
		model.addAttribute("user", user);
		model.addAttribute("project", project);
		return "modules/pro/assignAuth";
	}
	
	@RequiresPermissions("pro:project:edit")
	@RequestMapping(value = "updateCode")
	public String updateCode(String userId,String projectId,String code, RedirectAttributes redirectAttributes){
		ProjectUser param = new ProjectUser();
		User user = new User(userId);
		param.setUser(user);
		param.setProjectId(projectId);
		param.setCode(Integer.parseInt(code));
		projectUserService.updateCode(param);
		addMessage(redirectAttributes, "分配成功！");
		return "redirect:" + adminPath + "/pro/project/assign?id="+projectId;
	}
	/**
	 * 人员分配 -- 打开人员分配对话框
	 * @param role
	 * @param model
	 * @return
	 */
	@RequiresPermissions("pro:project:view")
	@RequestMapping(value = "usertoproject")
	public String selectUserToProject(Project project,Model model) {
		List<User> userList = systemService.getByProjectId(project.getId());
		project = projectService.get(project.getId());
		model.addAttribute("project", project);
		model.addAttribute("userList", userList);
		model.addAttribute("selectIds", Collections3.extractToString(userList, "name", ","));
		model.addAttribute("officeList", officeService.findAll());
		return "modules/pro/selectUserToProject";
	}
	
	/**
	 * 人员分配
	 * @param role
	 * @param idsArr
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("pro:project:edit")
	@RequestMapping(value = "assignrole")
	public String assignRole(Project project, String[] idsArr, RedirectAttributes redirectAttributes) {
		StringBuilder msg = new StringBuilder();
		int newNum = 0;
		String names = "";
		for (int i = 0; i < idsArr.length; i++) {
			User user = projectService.assignUserToProject(project, systemService.getUser(idsArr[i]));
			if (null != user) {
				msg.append("<br/>新增用户【" + user.getName() + "】到项目【" + project.getName() + "】！");
				newNum++;
				names = names + "," + user.getName();
			}
		}
		//项目日志
		ProLog proLog = new ProLog();
		proLog.setModule(ProLog.PROJECT);
		proLog.setModuleid(project.getId());
		proLog.setData(StringUtils.isEmpty(names)?names:names.substring(1));
		proLog.setType(ProLog.ASSIGN_MEMBER);
		proLog.setProject(project);
		proLogService.save(proLog);
		addMessage(redirectAttributes, "已成功分配 "+newNum+" 个用户"+msg);
		return "redirect:" + adminPath + "/pro/project/assign?id="+project.getId();
	}
	
	@RequiresPermissions("pro:project:edit")
	@RequestMapping(value = "outProject")
	public String outProject(String userId, String projectId, RedirectAttributes redirectAttributes){
		User user = systemService.getUser(userId);
		Project project = projectService.get(projectId);
		// 负责人不能被移除
		if (null != user && null != project && null != project.getManager()) {
			if (user.getId().equals(project.getManager().getId())) {
				addMessage(redirectAttributes, "负责人不能被移除！");
				return "redirect:" + adminPath + "/pro/project/assign?id="+projectId;
			}
			// 有未完成任务的成员不能被删除
			ProjectTask projectTask = new ProjectTask();
			projectTask.setProject(project);
			projectTask.setManager(user);
			Integer count = projectTaskService.findByProjectIdAndStatus(projectTask);
			if (count > 0) {
				addMessage(redirectAttributes, "该成员有未归档的任务！");
				return "redirect:" + adminPath + "/pro/project/assign?id="+projectId;
			}
		}
		Boolean flag = projectService.outProject(project, user);
		if (!flag) {
			addMessage(redirectAttributes, "用户【" + user.getName() + "】从项目【" + project.getName() + "】中移除失败！");
		}else {
			//项目日志
			ProLog proLog = new ProLog();
			proLog.setModule(ProLog.PROJECT);
			proLog.setModuleid(project.getId());
			proLog.setData(user.getName());
			proLog.setType(ProLog.REMOVE_MEMBER);
			proLog.setProject(project);
			proLogService.save(proLog);
			addMessage(redirectAttributes, "用户【" + user.getName() + "】从项目【" + project.getName() + "】中移除成功！");
		}
		return "redirect:" + adminPath + "/pro/project/assign?id="+projectId;
	}

	@RequiresPermissions("pro:project:view")
	@RequestMapping(value = "form")
	public String form(Project project, Model model) {
		model.addAttribute("project", project);
		return "modules/pro/projectForm";
	}

	@RequiresPermissions("pro:project:edit")
	@RequestMapping(value = "save")
	public String save(Project project, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, project)){
			return form(project, model);
		}
		projectService.save(project);
		addMessage(redirectAttributes, "保存项目成功");
		return "redirect:"+Global.getAdminPath()+"/pro/project/?repage";
	}
	
	@RequiresPermissions("pro:project:edit")
	@RequestMapping(value = "delete")
	public String delete(Project project, RedirectAttributes redirectAttributes) {
		ProjectTask projectTask = new ProjectTask();
		projectTask.setProject(new Project(project.getId()));
		Integer count = projectTaskService.findByProjectIdAndStatus(projectTask);
		if (count > 0) {
			addMessage(redirectAttributes, "有未完成任务，不能归档");
			return "redirect:"+Global.getAdminPath()+"/pro/project/?repage";
		}
		projectService.delete(project);
		addMessage(redirectAttributes, "归档项目成功");
		return "redirect:"+Global.getAdminPath()+"/pro/project/?repage";
	}
	@RequiresPermissions("pro:project:edit")
	@RequestMapping(value = "getByName")
	@ResponseBody
	public String getByName(Project project) {
		String result = "false";
		Project resultProject = projectService.getByName(project);
		if (null == resultProject || resultProject.getId().equals(project.getId())) {
			result = "true";
		}
		return result;
	}

	/**
	 * 甘特图
	 * @param project
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "ganttViewData")
	public String ganttViewData(Project project,HttpServletRequest request,Model model){
		model.addAttribute("e", project);
		String task = request.getParameter("task");
		if ("task".equals(task)) {
			String groupId = request.getParameter("groupId");
			model.addAttribute("groupId", groupId);
			return "modules/pro/ganttViewTask";
		}
		return "modules/pro/ganttView";
	}
	
	@RequestMapping(value = "ganttViewJson")
	@ResponseBody
	public String ganttViewJson(HttpServletRequest request){
		String projectId = request.getParameter("projectId");
		//首先查任务组
		TaskGroup taskGroupParam = new TaskGroup();
		taskGroupParam.setProject(new Project(projectId));
		List<Map<String, Object>> resultData = new ArrayList<>();
		List<TaskGroup> taskGroups = taskGroupService.findList(taskGroupParam);
		for (int i = 0; i < taskGroups.size(); i++) {
			TaskGroup taskGroup = taskGroups.get(i);
			Map<String, Object> taskGroupMap = new HashMap<>();
			taskGroupMap.put("id", taskGroup.getId());
			taskGroupMap.put("name", taskGroup.getName());
			taskGroupMap.put("tasks", new ArrayList<>());
			if (taskGroup.getStillQuantity() > 0) {
				ProjectTask projectTask = new ProjectTask();
				projectTask.setTaskGroup(taskGroup);
				//设置状态为11表示甘特图查找，需要查询所有数据，包括归档了的
				//status字段现在其实没有使用
				projectTask.setStatus("11");
				List<ProjectTask> projectTasks = projectTaskService.findList(projectTask);
				taskGroupMap.put("tasks", projectTasks);
			}
			resultData.add(taskGroupMap);
		}
		return JsonMapper.toJsonString(resultData);
	}
}